import 'dart:async';
import 'package:flutter/material.dart';

class CompleterDemoPage extends StatefulWidget {
  const CompleterDemoPage({super.key});

  @override
  State<CompleterDemoPage> createState() => _CompleterDemoPageState();
}

class _CompleterDemoPageState extends State<CompleterDemoPage> {
  final Completer<String> _completer = Completer<String>();
  String _result = "等待用户点击...";

  @override
  void initState() {
    super.initState();

    _completer.future.then((value) {
      setState(() {
        _result = "用户点击了：$value";
      });
    });
  }

  void _onClick(String btn) {
    if (!_completer.isCompleted) {
      _completer.complete(btn);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Completer 示例")),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(_result),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => _onClick("确认"),
              child: const Text("确认"),
            ),
            ElevatedButton(
              onPressed: () => _onClick("取消"),
              child: const Text("取消"),
            ),
          ],
        ),
      ),
    );
  }
}
